<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-03-02 17:44:35
 * @LastEditors: Sam
 * @LastEditTime: 2022-10-14 11:40:29
 */
namespace app\admin\controller;
use app\__MODULE__\model\{Goods as GoodsModel,Order,StoreCategory,GoodsAttr,ProductRule,GoodsAttrResult,GoodsAttrValue,GoodsComment,User,GoodsCollection};
use think\facade\Db;
use app\common\BaseController;

class Record extends BaseController {



    /**
     * 异步获取商品数据
     * @return void
     * @author Sam
     * @date 2022-03-02
     */
    public function get_echarts_product(){
        list($type,$data) = [request()->param('type'),request()->param('data')];
        $legdata = ['销量', '数量', '收藏'];
        $model = GoodsModel::setWhereType(GoodsModel::order('create_time asc,id desc'), $type);
        $list = GoodsModel::getModelTime(compact('data'), $model)
            ->field('FROM_UNIXTIME(create_time,"%Y-%c-%d") as un_time,count(id) as count,sum(sales) as sales')
            ->group('un_time')
            ->distinct(true)
            ->select()
            ->each(function ($item) use ($data) {
                $item['collect'] = GoodsModel::getModelTime(compact('data'), new GoodsCollection)->count();
            })->toArray();

        $chatrList = [];
        $datetime = [];
        $data_item = [];
        $itemList = [0 => [], 1 => [], 2 => []];
        foreach ($list as $item) {
            $itemList[0][] = $item['sales'];
            $itemList[1][] = $item['count'];
            $itemList[2][] = $item['collect'];
            array_push($datetime, $item['un_time']);
        }
        foreach ($legdata as $key => $leg) {
            $data_item['name'] = $leg;
            $data_item['type'] = 'line';
            $data_item['data'] = $itemList[$key];
            $chatrList[] = $data_item;
            unset($data_item);
        }
        unset($leg);
        // $badge = self::getbadge(compact('data'), $type);
        $count = GoodsModel::setWhereType(GoodsModel::getModelTime(compact('data'), new GoodsModel), $type)->count();
        \json_response(200,'success',compact('datetime', 'chatrList', 'legdata', 'count'));
    }
    


    /**
     * 收藏排行
     * @return void
     * @author Sam
     * @date 2022-03-02
     */
    public function get_echarts_collection(){
        $data = request()->param('data');
        $model = GoodsCollection::with(['goods'],'inner');
        $list  = [];
        $list['list']  = GoodsCollection::getModelTime(compact('data'),$model,'create_time')
                ->field('id,uid,goods_id,count(id) as number')
                ->group('goods_id')
                ->order('number desc')
                ->limit(10)
                ->select();
        $list['all_count'] = GoodsCollection::getModelTime(compact('data'),$model,'create_time')->count();
        json_response(1,'success',$list);
    }


    /**
     * 待补货商品
     * @return void
     * @author Sam
     * @date 2022-03-02
     */
    public function get_echarts_stock(){
        $list  = GoodsModel::field('id,store_name,image,stock,price')->where('stock','<',3)->limit(20)->select();
        json_response(1,'success',$list);
    }
    
    /**
     * 销售排行
     * @return void
     * @author Sam
     * @date 2022-03-03
     */
    public function get_echarts_profity(){
        $data = request()->param('data');
        $classs = ['layui-bg-red', 'layui-bg-orange', 'layui-bg-green', 'layui-bg-blue', 'layui-bg-cyan'];
        $model = Order::alias('a')
            ->join('OrderCartInfo c', 'a.id=c.oid')
            ->join('goods b', 'b.id=c.product_id')
            ->where('b.is_show', 1)
            ->where('b.is_del', 0)
            ->where('a.paid',1)
            ->where('a.status','in',[3,7,6]);
        $list = GoodsModel::getModelTime(compact('data'), $model, 'a.add_time')
            ->group('c.product_id')
            ->order('profity desc')
            ->limit(10)
            ->field(['count(c.product_id) as p_count', 'b.store_name','b.image', 'sum(b.price) as sum_price', 'sum(a.pay_price) as profity'])
            ->select();
        if (count($list)) $list = $list->toArray();
        $maxList = [];
        $sum_count = 0;
        $sum_price = 0;
        foreach ($list as $item) {
            $sum_count += $item['p_count'];
            $sum_price = bcadd($sum_price, $item['profity'], 2);
        }
        foreach ($list as $key => &$item) {
            $item['w'] = sprintf("%.2f",  bcdiv($item['profity'], $sum_price, 2) * 100);
            $item['class'] = isset($classs[$key]) ? $classs[$key] : (isset($classs[$key - count($classs)]) ? $classs[$key - count($classs)] : '');
            // $item['store_name'] = self::getSubstrUTf8($item['store_name'], 30);
        }
        $maxList['sum_count'] = $sum_count;
        $maxList['sum_price'] = $sum_price;
        $maxList['list'] = $list;
        json_response(1,'success',$maxList);
    }

        /**
     * 获取退货商品
     */
    public function getTuiPriesList()
    {
        $perd = Order::alias('s')->join('OrderCartInfo c', 's.id=c.oid')
            ->field('count(c.product_id) as count,c.product_id as id')
            ->group('c.product_id')
            ->where('s.status',5)
            ->order('count desc')
            ->limit(10)
            ->select();
        if (count($perd)) $perd = $perd->toArray();
        foreach ($perd as &$item) {
            $item['store_name'] = GoodsModel::where(['id' => $item['id']])->value('store_name');
            $item['store_image'] = GoodsModel::where(['id' => $item['id']])->value('image');
            $item['price'] = GoodsModel::where(['id' => $item['id']])->value('price');
        }
        json_response(1,'success',$perd);
    }

    /**
     * 订单数据
     * @return void
     * @author Sam
     * @date 2022-03-03
     */
    public function chart_order()
    {
        $this->assign([
            'is_layui' => true,
            'year' => get_month()
        ]);
        return $this->fetch();
    }

    /**
     * 订单数据
     * @return void
     * @author Sam
     * @date 2022-03-03
     */
    public function get_echarts_order(){
        $where = request()->param();
        $orderlist = Order::setEchatWhere($where)->field(
            'FROM_UNIXTIME(add_time,"%Y-%m-%d") as add_date,sum(total_num) total_num,count(*) count,sum(total_price) total_price,sum(refund_price) refund_price,group_concat(cart_id SEPARATOR "|") cart_ids'
        )->group('add_date')->order('add_date asc')->select();
       
        count($orderlist) && $orderlist = $orderlist->toArray();
        $legend = ['商品数量', '订单数量', '订单金额', '退款金额'];
        $seriesdata = [
            [
                'name' => $legend[0],
                'type' => 'line',
                'data' => [],
            ],
            [
                'name' => $legend[1],
                'type' => 'line',
                'data' => []
            ],
            [
                'name' => $legend[2],
                'type' => 'line',
                'data' => []
            ],
            [
                'name' => $legend[3],
                'type' => 'line',
                'data' => []
            ]
        ];
        $xdata = [];
        $zoom = '';
        foreach ($orderlist as $item) {
            $xdata[] = $item['add_date'];
            $seriesdata[0]['data'][] = $item['total_num'];
            $seriesdata[1]['data'][] = $item['count'];
            $seriesdata[2]['data'][] = $item['total_price'];
            $seriesdata[3]['data'][] = $item['refund_price'];
        }
 
        // count($xdata) > $limit && $zoom = $xdata[$limit - 5];
        $badge = Order::getOrderBadge($where);
        $bingpaytype = Order::setEchatWhere($where)->group('pay_type')->field('count(*) as count,pay_type')->select();
        count($bingpaytype) && $bingpaytype = $bingpaytype->toArray();
        $bing_xdata = ['微信支付', '其他支付'];
        $color = ['#ffcccc', '#99cc00'];
        $bing_data = [];
        foreach ($bingpaytype as $key => $item) {
            if ($item['pay_type'] == 1) {
                $value['name'] = $bing_xdata[0];
            } else if ($item['pay_type'] == 2) {
                $value['name'] = $bing_xdata[1];
            } 
            $value['value'] = $item['count'];
            $value['itemStyle']['color'] = isset($color[$key]) ? $color[$key] : $color[0];
            $bing_data[] = $value;
        }
        \json_response(1,'success',compact('zoom', 'xdata', 'seriesdata', 'badge', 'legend', 'bing_data', 'bing_xdata'));
    }


}
